package com.hongguan.oms.common;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.hongguan.oms.service.task.TaskInfoService;
import com.hongguan.oms.utils.Util;

/**
 * @author <a href="mailto:gaoxinyi@hongguaninfo.com">gaoxy</a>
 * @version createTime:2010-2-2 summary
 */
@Service
public class Uploader {
	protected static final Logger logger = LoggerFactory.getLogger(Uploader.class);
	private static final String FILE_NAME = "fileName";
	private static final String HIDE_FILE_ID = "hideFileId";
	private String baseFolder;
	private String folder;
	private String type;
	private TaskInfoService service;

	// private String parameter = "fileName";

	public void setService(TaskInfoService service) {
		this.service = service;
	}

	public void setFolder(String f) {
		this.folder = f;
	}

	public void setBaseFolder(String f) {
		this.baseFolder = f;
	}

	public void setType(String type) {
		this.type = type;
	}

	private void checkBaseFolder(HttpServletRequest request) {
		if (this.baseFolder == null) {
			this.baseFolder = request.getSession().getServletContext().getRealPath("/") + "upload";
		}
	}

	private String getFilePath(HttpServletRequest request, String folder, String fileTimeName) {
		StringBuilder result = new StringBuilder(folder);
		result.append(fileTimeName);
		// result.append(Util.getLoginIdFromSession(request));
		// result.append(Util.getDateStamp());
		return result.toString();
	}

	private String getFolderPath(HttpServletRequest request) {
		checkBaseFolder(request);
		StringBuilder result = new StringBuilder(this.baseFolder);
		result.append("/");
		result.append(this.folder);
		result.append("/");
		result.append(new SimpleDateFormat("yyyyMM").format(new Date()));
		result.append("/");
		// result.append(Util.getDateSplit());
		// result.append("/");
		return result.toString();
	}

	private void createFolder(String path) {
		File dir = new File(path);
		if (!dir.exists())
			dir.mkdirs();
	}

	private boolean write(MultipartFile file, String filePath) {
		File f = new File(filePath);
		FileOutputStream fos;
		try {
			fos = new FileOutputStream(f);
			fos.write(file.getBytes());
			fos.flush();
			fos.close();
		} catch (FileNotFoundException e) {
			logger.error("Can not write file error! FilePath = " + filePath);
			return false;
		} catch (IOException e) {
			logger.error("Can not write file error! FilePath = " + filePath);
			return false;
		}
		return true;
	}

	public void modifyUpload(HttpServletRequest request, String busiId) {
		if (!Util.isUserId(request))
			return;
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> files = multipartRequest.getFileMap();
		Map<String, String[]> map = request.getParameterMap();
		Map<String, String> ids = new HashMap<String, String>();
		for (Entry<String, String[]> entry : map.entrySet()) {
			String key = entry.getKey();
			String[] value = entry.getValue();
			if (key != null && key.length() > 0 && value != null && value.length > 0 && value[0] != null
					&& value[0].length() > 0 && key.indexOf(HIDE_FILE_ID) == 0) {
				key = key.substring(HIDE_FILE_ID.length(), key.length());
				ids.put(key, value[0]);
			}
		}
		if (files != null && !files.isEmpty()) {
			for (MultipartFile file : files.values()) {
				if (file == null)
					continue;
				String name = file.getName();
				String fileName = file.getOriginalFilename();
				if (name != null && name.length() > 0 && fileName != null && fileName.length() > 0
						&& name.indexOf(FILE_NAME) == 0) {
					name = name.substring(FILE_NAME.length(), name.length());
					ids.remove(name);
				}
			}
		}

		
		String[] fileIds = new String[ids.size()];
		fileIds = ids.values().toArray(fileIds);
		Map<String, Object> param = new HashMap<String, Object>(2);
		param.put("fileIds", fileIds);
		param.put("buisId", busiId);
		param.put("fileType", type);
		service.delMulUploadFile(param);
		uploadFile(request, files, busiId);
	}

	public int upload(HttpServletRequest request, String busiId) {
		if (!Util.isUserId(request))
			return 0;
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> files = multipartRequest.getFileMap();
		return uploadFile(request, files, busiId);
	}

	protected int uploadFile(HttpServletRequest request, Map<String, MultipartFile> files, String busiId) {
		int count=0;
		if (files == null || files.isEmpty())
			return count;
		for (MultipartFile file : files.values()) {
			if (file == null || file.getOriginalFilename() == null || file.getOriginalFilename().length() == 0)
				continue;
			String[] name = file.getOriginalFilename().split("\\.");

			String fileTimeName = System.currentTimeMillis() + "." + name[1];

			String folderPath = this.getFolderPath(request);
			createFolder(folderPath);
			String filePath = this.getFilePath(request, folderPath, fileTimeName);

			if (!write(file, filePath)){
				return count;
			}else{
				Map<String, Object> upLoadFile = new HashMap<String, Object>();
				upLoadFile.put("accessory_name", file.getOriginalFilename());
				upLoadFile.put("upload_date", new SimpleDateFormat("yyyy-MM-dd HH:mm").format(new Date()));
				upLoadFile.put("upload_name", fileTimeName);
				upLoadFile.put("file_path", this.folder + "/"
						+ new SimpleDateFormat("yyyyMM").format(new Date()));
				upLoadFile.put("file_size", file.getSize());
				upLoadFile.put("content_type", file.getContentType());
				upLoadFile.put("buis_id", busiId);
				upLoadFile.put("file_type", type);
				upLoadFile.put("file_uploader", Util.getUserIdFromSession(request));
				if(request.getParameter("fileRemark") != null && !"".equals(request.getParameter("fileRemark"))){
					upLoadFile.put("accessory_desc",request.getParameter("fileRemark"));
				}
				service.savaFileUploadInfo(upLoadFile);
				count++;
			}
		}
		return count;
	}

	public String downloadFile(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String fileId = request.getParameter("fileId");
		if (fileId == null || fileId.length() == 0)
			return null;
		this.checkBaseFolder(request);
		Map<String, Object> filemap = service.getUploadFileInfo(fileId);
		String localName = (String) filemap.get("ACCESSORY_NAME");
		
		String FILE_PATH = (String) filemap.get("FILE_PATH");
		String UPLOAD_NAME = (String) filemap.get("UPLOAD_NAME");
		
		String contentType = (String) filemap.get("CONTENT_TYPE");

		localName = new String(localName.getBytes("GBK"), "iso-8859-1");
		response.setContentType(contentType);
		response.setHeader("Content-disposition", "attachment; filename=" + localName);

		File file = new File(this.baseFolder+"/"+ FILE_PATH+"/"+UPLOAD_NAME);
		FileCopyUtils.copy(new BufferedInputStream(new FileInputStream(file)), response.getOutputStream());

		return null;
	}

	public List searchUpLoadFile(Map<String, Object> param) throws Exception {
		return service.searchTaskUpLoadFile(param);
	}
	// public String upLoad(HttpServletRequest request) throws Exception{
	// if(!Util.isUserId(request)){
	// return null;
	// }else{
	// MultipartHttpServletRequest multipartRequest =
	// (MultipartHttpServletRequest) request;
	// MultipartFile file = (MultipartFile)
	// multipartRequest.getFile("fileName");
	// if (file == null) {
	// return null;
	// } else {
	// String loginId = Util.getLoginIdFromSession(request);
	// String op = request.getParameter("fileName");
	// String dirName = "upload/" + folder + loginId;
	// String dir = request.getRealPath("/") + dirName;
	// String fileName = "/" + loginId + Util.getDateStamp() +
	// op.substring(op.lastIndexOf("."));
	// File directior = new File(dir);
	// if (!directior.exists())
	// directior.mkdir();
	// File file2 = new File(dir + fileName);
	// FileOutputStream fos = new FileOutputStream(file2);
	// fos.write(file.getBytes());
	// fos.close();
	// return dir + fileName;
	// }
	// }
	// }
}
